#'
#'  Project title:     'Sovereign Risk and Government Change: Elections, Ideology and Experience'
#'  Authors:           Sarah M. Brooks; Raphael Cunha; Layna Mosley
#'  File description:  Plots bond market reaction to 2018 Mexican presidential election
#'  Output:            Figure 3
#'

# my_packages <- c("tidyverse", "scales", "roll", "cowplot")
# install.packages(my_packages)

library(foreign)
library(tidyverse)
library(scales)
library(roll)
library(cowplot)

# Set directories

DATADIR <- "/.../Data/Daily"

# Load Mexico EMBI+ data

mex <- read.csv(file.path(DATADIR, "Mexico EMBI Plus.csv"),
                stringsAsFactors = FALSE)

mex$date <- as.Date(mex$date, "%m/%d/%Y")
mex$country <- "Mexico"

# Calculate daily changes in spread

Ret <- function(x){ #Daily return function
  
  c(NA, x[2:length(x)]/x[1:length(x)-1] - 1)
  
}

mex <- mex %>%
  mutate(rollsd = roll_sd(embispread, width = 30),
         d_embispread = c(NA, diff(embispread)),
         R_embispread = Ret(embispread))

# Plot

# Subset plotting data
mex_start_date <- as.Date( "2017-10-01") # Start date for plot
mex_election_date <- as.Date("2018-07-01") # 1st round date
mex_inauguration_date <- as.Date("2018-12-01")
mex_end_date <- as.Date("2019-05-01")

mex_plot <- subset(mex,
                   date >= mex_start_date &
                     date <= mex_end_date)

p1 <- ggplot(mex_plot, aes(x = date, y = embispread)) +
  geom_vline(aes(xintercept = mex_election_date), linetype = 3) +
  geom_vline(aes(xintercept = mex_inauguration_date), linetype = 3) +
  geom_line(colour = "grey40") +
  labs(title = NULL,
       x = NULL,
       y = "Bond spread") +
  #theme_bw(base_family = "Myriad Pro") +
  theme_bw() +
  theme(axis.text.x = element_blank(),
        plot.margin = unit(c(5.5,5.5,0,5.5), "pt")) +
  scale_x_date(labels = date_format("%b %Y")) +
  NULL

p2 <- ggplot(mex_plot, aes(x = date, y = rollsd)) +
  geom_vline(aes(xintercept = mex_election_date), linetype = 3) +
  geom_vline(aes(xintercept = mex_inauguration_date), linetype = 3) +
  geom_line(size = .6, colour = "tomato") +
  labs(x = NULL, y = "Bond spread volatility") +
  #theme_bw(base_family = "Myriad Pro") +
  theme_bw() +
  scale_x_date(labels = date_format("%b %Y")) +
  annotate("text", x = mex_election_date, vjust = -.3, y = 25, label = "Election", angle = 90, size = 3.5, family = "Myriad Pro") +
  annotate("text", x = mex_inauguration_date, vjust = -.3, y = 11, label = "AMLO takes office", angle = 90, size = 3.5, family = "Myriad Pro") +
  NULL

p_mex <- cowplot::plot_grid(p1, p2,
                            align = "v",
                            ncol = 1)
p_mex
